package com.agile.leetcode.lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author:ChenZhangKun
 * @Date: 2023/7/13 16:17
 */
public class LinkedHashMapLru<K,V> extends LinkedHashMap<K,V> {
    private final int capacity;

    /**
     * LinkedHashMap
     * - 1 put 有则覆盖，没有则插入，维护元素道文件末尾
     * - 2 get 有返回对应值，并将元素移到文件末尾
     * @param capacity
     */
    public LinkedHashMapLru( int capacity) {
        // 会根据访问顺序来维护元素
        super(capacity,0.75f,true);
        this.capacity = capacity;
    }

    /**
     * 插入元素后会回调
     * 返回为true时，会删除未访问的元素
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        System.out.println("调用removeEldestEntry方法了");
        return size()>capacity;
    }

    public static void main(String[] args) {

        LinkedHashMapLru<String,String> linkedHashMapLru=new LinkedHashMapLru<>(2);


        linkedHashMapLru.put("1","1");
        linkedHashMapLru.put("2","2");
        System.out.println(linkedHashMapLru.get("1"));
        linkedHashMapLru.put("3","3");
        System.out.println(linkedHashMapLru);
    }
}
